package com.example.service.impl;

import com.alibaba.dashscope.audio.tts.SpeechSynthesisAudioFormat;
import com.alibaba.dashscope.audio.tts.SpeechSynthesisParam;
import com.alibaba.dashscope.audio.tts.SpeechSynthesizer;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.example.dto.SoundDto;
import com.example.dto.SoundPageQueryDto;
import com.example.dto.SoundPutDto;
import com.example.entity.Sound;
import com.example.mapper.SoundMapper;
import com.example.properties.AliOssProperties;
import com.example.result.PageResult;
import com.example.service.SoundService;
import com.example.utils.AliOssUtil;
import com.example.vo.SoundVo;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class SoundServiceImpl implements SoundService {
    @Autowired
    private SoundMapper soundMapper;
    private static String prefix = "whutzhu";
    private static String targetModel = "cosyvoice-v1";
     @Autowired
     private AliOssProperties aliOssProperties;
     @Autowired
     private AliOssUtil aliOssUtil;

    @Override
    public PageResult pageQuery(SoundPageQueryDto soundPageQueryDto) {


        PageHelper.startPage(soundPageQueryDto.getPage(),soundPageQueryDto.getPageSize());
        Page<Sound> page = soundMapper.pageQuery(soundPageQueryDto);
        long total = page.getTotal();
        List<Sound> records = page.getResult();
        for (Sound record : records){
            log.info("文件url{}",record.getAudioUrl());
            System.out.println(record.getAudioUrl());
        }
        return new PageResult(total,records);
    }

    @Override
    public void upload(SoundDto soundDto) throws NoApiKeyException, InputRequiredException {
  /*      VoiceEnrollmentService service = new VoiceEnrollmentService(aliOssProperties.getApikey());
        Voice myVoice = service.createVoice(targetModel, prefix, soundDto.getAudioUrl());
        System.out.println("RequestId: " + service.getLastRequestId());
        System.out.println("your voice id is " + myVoice.getVoiceId());

       sound.setModelId(myVoice.getVoiceId());*/
        Sound sound=new Sound();
        BeanUtils.copyProperties(soundDto,sound);
        sound.setUploadedAt(LocalDateTime.now());
        soundMapper.upload(sound);
        log.info("文件上传成功");
    }

    @Override
    public void deleteById(Integer id) {
        soundMapper.deleteById(id);

    }

    @Override
    public void update(SoundDto soundDto) {
        Sound sound=new Sound();
        BeanUtils.copyProperties(soundDto,sound);
        soundMapper.update(sound);
    }

    @Override
    public SoundVo getById(Integer id) {

        Sound sound = soundMapper.getById(id);
        SoundVo soundVo = new SoundVo();
        BeanUtils.copyProperties(sound,soundVo);
        return soundVo;
    }

    @Override
    public List<Sound> getAllSound() {
        List<Sound> sounds = soundMapper.getAllSound();
        return sounds;
    }

    @Override
    public String generate(SoundPutDto soundPutDto) throws IOException {
        log.info("合成声音");
        Sound sound = soundMapper.getById(soundPutDto.getVoiceId());
        SpeechSynthesizer synthesizer = new SpeechSynthesizer();
        SpeechSynthesisParam param = SpeechSynthesisParam.builder()
                .model(sound.getModelId())
                .text(soundPutDto.getText())
                .sampleRate(48000)
                .format(SpeechSynthesisAudioFormat.WAV)
                .apiKey(aliOssProperties.getApikey())
                .build();

        File file = new File("output.wav");
        // 调用call方法，传入param参数，获取合成音频
        ByteBuffer audio = synthesizer.call(param);
        try (FileOutputStream fos = new FileOutputStream(file)) {
            fos.write(audio.array());
            System.out.println("synthesis done!");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String url = aliOssUtil.upload(audio.array(), UUID.randomUUID()+"output.wav");
        FileUtils.delete(file);
        return url;

    }
}
